package net.zjitc.service.impl;

import net.zjitc.dao.AdminProductDao;
import net.zjitc.dao.CartDao;
import net.zjitc.dao.OrderDao;
import net.zjitc.dao.impl.AdminProductDaoImpl;
import net.zjitc.dao.impl.CartDaoImpl;
import net.zjitc.dao.impl.OrderDaoImpl;
import net.zjitc.pojo.Order;
import net.zjitc.pojo.Orderitem;
import net.zjitc.pojo.Product;
import net.zjitc.pojo.User;
import net.zjitc.service.AdminProductService;
import net.zjitc.service.OrderService;
import net.zjitc.utils.db.C3P0Utils;

import java.sql.SQLException;
import java.util.List;

/**
 * Created by Administrator on 2017/12/13.
 */
public class OrderServiceImpl implements OrderService{
    OrderDao dao=new OrderDaoImpl();
    CartDao cartDao=new CartDaoImpl();
    AdminProductDao productDao=new AdminProductDaoImpl();
    public int add(Order order) {
        try {
            //开启事务
            C3P0Utils.startTransation();
            //购物车清空与生成订单看成一个业务，要同时操作成功才可以
            //所以放进同一个事务里
            int count=dao.add(order);
            cartDao.clearCart(order.getUser());
            //提交事务
            C3P0Utils.commitTransation();
            return count;
        } catch (SQLException e) {
            try {
                C3P0Utils.rollbackTransation();//回滚
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
            e.printStackTrace();
        }
        return 0;
    }

    public List<Order> findByUid(int uid) {
        //找到订单列表
        List<Order> orders=dao.findByUid(uid);
        for (Order o:orders){
            //通过订单号找到对应的订单项
            List<Orderitem> orderitemList=dao.findOrderitemByOid(o.getOid());
            //通过pid找到订单项对应的的产品
            for (Orderitem orderitem:orderitemList){
                //通过Iitemid找到订单项对应的的pid
                int spid=dao.findPidByItemid(orderitem.getItemid());
                String pid=String.valueOf(spid);

                Product product=productDao.findByPid(pid);
                //设置订单项的产品
                orderitem.setProduct(product);
            }
            o.setOrderitemList(orderitemList);
        }
        return orders;
    }

    public List<Order> findAll() {
        return dao.findAll();
    }

    public List<Order> findbyState(int state) {
        return dao.findbyState(state);
    }

    public int editState(String oid) {
        return dao.editState(oid);
    }

    public int editPayState(String oid) {
        return dao.editPayState(oid);
    }

    public int editStateFour(String oid) {
        return dao.editStateFour(oid);
    }

    public int editOstate(String oid) {
        List<Orderitem> orderitemList=dao.findOrderitemByOid(oid);
        for (Orderitem o:orderitemList){
            int count=dao.editOstate(o.getItemid());
        }
        return 1;
    }

    public int editOstateByItemid(String itemid) {
        return dao.editOstateByItemid(itemid);
    }


}
